/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: DesityUtils.java
 *   @Date: 19-1-2 下午4:08
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.baselib.utils;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;

/**
 * 一刀切，不合适
 * https://www.cnblogs.com/whycxb/p/9755012.html
 */
public class DesityUtils {
    private static float sNonCompatDensity;
    private static float sNonCompatScaleDensity;

    public static void setCustomDesity(@NonNull Activity activity, @NonNull final Application application){
        DisplayMetrics appDisplayMetrics = application.getResources().getDisplayMetrics();
        if (sNonCompatDensity==0) {
            sNonCompatDensity = appDisplayMetrics.density;
            sNonCompatScaleDensity = appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale>0) {
                        sNonCompatScaleDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }

        float targetDesity  = appDisplayMetrics.widthPixels / 360;
        float targetScaledDensity = targetDesity * (sNonCompatScaleDensity / sNonCompatDensity);
        int targetDesityDpi = (int) (160 * targetDesity);

        appDisplayMetrics.density = targetDesity;
        appDisplayMetrics.scaledDensity = targetScaledDensity;
        appDisplayMetrics.densityDpi = targetDesityDpi;

        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDesity;
        activityDisplayMetrics.scaledDensity = targetDesity;
        activityDisplayMetrics.densityDpi = targetDesityDpi;

    }
}
